package com.group4.Servlets;

import java.awt.Desktop;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import com.dropbox.core.*;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.DropboxInputStream;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.RequestTokenPair;
import com.dropbox.client2.session.WebAuthSession;
import com.dropbox.client2.session.Session.AccessType;
import com.dropbox.client2.session.WebAuthSession.WebAuthInfo;
import com.group4.DAO.VideoDAO;
import com.group4.DB.User;
import com.group4.DB.Video;




/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String UPLOAD_DIRECTORY = "uploadDirectory";
	private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
	private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
	private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
	// App key & secret that Dropbox's developer website gives your app
		 // Key Received @ step 1.5
		 private static final String APP_KEY = "er5w2xvmizhmuis";
		 // Secret Received @ step 1.5
		 private static final String APP_SECRET = "t3ilbtbl6sy247n";
		 private static final String ACCESS_TOKEN_KEY = "fyUV5eotX0ruRIJ4";
		 private static final String ACCESS_TOKEN_SECRET = "XBtPd4XS2CbvK1M5";
		 
		 // Permission type created @ step 1.4
		 private static final AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
		 private static DropboxAPI<WebAuthSession> mDBApi;
		 
		 
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		String description = null;// = (String)request.getParameter("description");
        String tags = null;// = (String)request.getParameter("tags");
		//final String APP_KEY = "er5w2xvmizhmuis";
        //final String APP_SECRET = "t3ilbtbl6sy247n";

        DbxAppInfo appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);

        DbxRequestConfig config = new DbxRequestConfig("JavaTutorial/1.0",
            Locale.getDefault().toString());
        DbxWebAuthNoRedirect webAuth = new DbxWebAuthNoRedirect(config, appInfo);
        System.out.println(System.getProperty("user.dir"));
        
        /*
        // Have the user sign in and authorize your app.
        String authorizeUrl = webAuth.start();
        System.out.println("1. Go to: " + authorizeUrl);
        System.out.println("2. Click \"Allow\" (you might have to log in first)");
        System.out.println("3. Copy the authorization code.");
        String code = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
        
        // This will fail if the user enters an invalid authorization code.
        DbxAuthFinish authFinish = null;
		try {
			authFinish = webAuth.finish(code);
		} catch (DbxException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
        String accessToken = authFinish.accessToken;
        System.out.println(accessToken);
        System.out.println("hlvazTU5lzMAAAAAAAAFfTZO7N1rAobznppffP-9sBPKHYavZDjLyFsbQ9ADH4us");
        */
        String accessToken = "hlvazTU5lzMAAAAAAAAFfTZO7N1rAobznppffP-9sBPKHYavZDjLyFsbQ9ADH4us";
        
        DbxClient client = new DbxClient(config, accessToken);

        try {
			System.out.println("Linked account: " + client.getAccountInfo().displayName);
		} catch (DbxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
        
        
        // checks if the request actually contains upload file
 		if (!ServletFileUpload.isMultipartContent(request)) {
 		    PrintWriter writer = response.getWriter();
 		    writer.println("Request does not contain upload data");
 		    writer.flush();
 		    return;
 		}
 		// configures upload settings
 		DiskFileItemFactory factory = new DiskFileItemFactory();
 		factory.setSizeThreshold(THRESHOLD_SIZE);
 		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 		 
 		ServletFileUpload upload = new ServletFileUpload(factory);
 		upload.setFileSizeMax(MAX_FILE_SIZE);
 		upload.setSizeMax(MAX_REQUEST_SIZE);
 		
 		
 		// constructs the directory path to store upload file
 		String uploadPath = getServletContext().getRealPath("")
 		    + File.separator + UPLOAD_DIRECTORY;
 		System.out.println("uploadPath " + uploadPath);
 		// creates the directory if it does not exist
 		File uploadDir = new File(uploadPath);
 		System.out.println("uploadDir " + uploadDir);
 		
 		List formItems = null;
		try {
			formItems = upload.parseRequest(new ServletRequestContext(request));
		} catch (FileUploadException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//.parseRequest(request);
        Iterator iter = formItems.iterator();
        
        File inputFile = null;
        InputStream inputStream = null;
        String fileName = "/";
        long size = 0;
     // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
            	
                fileName = fileName + new File(item.getName()).getName();
                System.out.println("filename " + fileName);
                //String filePath = uploadPath + File.separator + fileName;
                //System.out.println("filePath " + filePath);
                //inputFile = new File(filePath);
                 
            	inputStream = item.getInputStream();
            	size = item.getSize();
                // saves the file on disk
                //item.write(storeFile);
            }else{
            	String name = item.getFieldName();
            	if(name.equals("description")){
            		description = item.getString();
            	}else if(name.equals("tags")){
            		tags = item.getString();
            	}
            	
            }
        }
        
       
        //File inputFile = new File("../../../../başlangıç.txt");
        //String fileName = "/" + inputFile.getName();
        //System.out.println(fileName);
        //FileInputStream inputStream = new FileInputStream(inputFile);
        try {
            DbxEntry.File uploadedFile = null;
			try {
				uploadedFile = client.uploadFile(fileName,
				    DbxWriteMode.add(), size, inputStream);
			} catch (DbxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            System.out.println("Uploaded: " + uploadedFile.toString());
        } finally {
            inputStream.close();
        }

        DbxEntry.WithChildren listing = null;
		try {
			listing = client.getMetadataWithChildren("/");
		} catch (DbxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println("Files in the root path:");
        for (DbxEntry child : listing.children) {
            System.out.println("	" + child.name + ": " + child.toString());
        }
        String url = null;
        try {//gets the download link
			url = client.createShareableUrl(fileName);
			url = url.substring(0, url.length()-1) + "1";
			//System.out.println(url);
		} catch (DbxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        HttpSession session = request.getSession();
        
        
        
        String username = (String) session.getAttribute("username");
        VideoDAO video = new VideoDAO();
        video.setVideoUploaderID(User.getUserWithUsername(username).getID());
        video.setVideoUrl(url);
        video.setVideoName(fileName.substring(1));
        video.setVideoDescription(description);
        video.setVideoTag(tags);
        video.setVideoUploadDateTime(new java.sql.Date(new java.util.Date().getTime()));
        Video.addVideo(video);
        
        RequestDispatcher rd = request.getRequestDispatcher("/user/profile.jsp");
		rd.forward(request, response);
        
        /*
        FileOutputStream outputStream = new FileOutputStream("magnum-opus.txt");
        try {
            DbxEntry.File downloadedFile = null;
			try {
				downloadedFile = client.getFile("/magnum-opus.txt", null,
				    outputStream);
			} catch (DbxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            System.out.println("Metadata: " + downloadedFile.toString());
        } finally {
            outputStream.close();
        }
		*/
		
		
		
		
		// Initialize the goods/session
		/*
		  AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
		  WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE);
		  // Initialize DropboxAPI object
		  mDBApi = new DropboxAPI<WebAuthSession>(session);
		
		
		// checks if the request actually contains upload file
		if (!ServletFileUpload.isMultipartContent(request)) {
		    PrintWriter writer = response.getWriter();
		    writer.println("Request does not contain upload data");
		    writer.flush();
		    return;
		}
		// configures upload settings
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(THRESHOLD_SIZE);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		 
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(MAX_REQUEST_SIZE);
		
		
		// constructs the directory path to store upload file
		String uploadPath = getServletContext().getRealPath("");
		// creates the directory if it does not exist
		File uploadDir = new File(uploadPath);
		
		if (!uploadDir.exists()) {
		    uploadDir.mkdir();
		}
		
		
		try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(new ServletRequestContext(request));
            Iterator iter = formItems.iterator();
             
            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    File storeFile = new File(fileName);
                    
                    InputStream inputStream = new FileInputStream(storeFile);
                    mDBApi.putFile("/Videos/", inputStream, storeFile.length(), null, null);
                    
                    
                    // saves the file on disk
                    //item.write(storeFile);
                }
            }
            request.setAttribute("message", "Upload has been done successfully!");
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
		*/
		
		
	}

}
